/**
 * Created by duzi on 7/7/15.
 */
$(document).ready(function(){
    var table = {
        $table:$('#showTable'),
        $input: $('#tableSearchInput'),
        ids: {
            'supplier': 'supplierName',
            'customer': 'customerName',
            'product': 'productName',
            'category': 'categoryName'
        },
        search: function(table, value){
            var self = this;
            $.ajax({
                type: "GET",
                url: '/' + table + (value ? '/' + value : ''),
                contentType: 'application/json',
                success: function(response){
                    if(response.length == 0 || response.errorMsg){
                        alert('沒有東西哦~');
                        self.$table.parent().css('display', 'none');
                        return;
                    }
                    if(!response[0]){
                        var c = [];
                        c.push(response);
                        response = c;
                    }
                    var headHtml  = '<tr>';
                    Object.keys(response[0]).forEach(function(key){
                        headHtml += '<th>' + key + '</th>';
                    })
                    self.$table.find('thead').html(headHtml + '</tr>');

                    var bodyHtml = '';
                    response.forEach(function(item){
                       bodyHtml += '<tr>';
                        Object.keys(item).forEach(function(key){
                            /*here is the damn if else*/
                            var content = item[key];
                            if(/(time)|(birthday)/.test(key) && content){
                                var date = new Date(item[key]);
                                content = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
                                bodyHtml += '<td>';
                            }else if(typeof content == 'object' && content){
                                content = content[self.ids[key]] || content[key + 'Id'];
                                bodyHtml += '<td>';
                            }else if(/(id)|(stock)/i.test(key)){
                                bodyHtml += '<td>';
                            }else{
                                bodyHtml += '<td class="editable" data-key="'+ key +'">'
                            }

                            bodyHtml +=  content  + '</td>';
                        })
                        bodyHtml += '<td class="fui-cross deleteRecord"></td></tr>';
                    });
                    self.$table.find('tbody').html(bodyHtml);
                    self.$table.parent().css('display', 'block');
                }
            })
        },
        change: function(id, key, value){
            var table = this.$table.data('table');
            table = table.substring(0, table.length - 1);
            if(/(supplier)|(category)/.test(key)){ key = key + '_id'}
            key = key.replace(/([A-Z])/g, function(target){return '_'+target.toLocaleLowerCase()});

            $.ajax({
                type: "PUT",
                url: "/base",
                data: JSON.stringify({id: id, key: key, value: value, table:table}),
                contentType: 'application/json',
                success: function(response){
                    alert("修改成功 ~");
                }
            })
        },
        dele: function(table,id){
            var self = this;
            $.ajax({
                type: "DELETE",
                url: "/" + table,
                data: JSON.stringify({id: id}),
                contentType: 'application/json',
                success: function(response){
                    alert("delete成功 ~");
                    self.search(table);
                }
            })
        },
        add: function(table){
            var self =  this;
            $.ajax({
                type: "POST",
                url: "/search/" + table,
                data: JSON.stringify({}),
                contentType: 'application/json',
                success: function(response){
                    var html  = '<tr><td> ' + response + '</td>';
                    for(var i = 1; i < self.$table.find('th').length; i++){
                        html += '<td class="editable" data-key=" '+ self.$table.find('th').eq(i).text() +'"></td>';
                    }
                    html += '<td class="fui-cross deleteRecord"></td></tr>'
                    self.$table.find('tbody').append(html);
                }
            })
        },
        event: function(){
            var self = this;
            $('.dropdown-menu').on('click', 'a', function(e){
                $(this).parents('.dropdown-menu').prev('.dropdown-toggle').text(this.innerText);
            });
            $('#table-selector').on('click', 'a', function(e){
                var table = $(this).data('table');
                self.$table.data('table',table);
                self.search(table, self.$input.val());
            });
            this.$input.on('keyup', function(e){
               if(!this.value) return;
               if(e.keyCode == 13){
                   self.search(self.$table.data('table'), this.value);
               }
            });

            this.$table.find('tbody').on('click','td.editable', function(){
                $(this).attr('contentEditable', true);
            })

            this.$table.find('tbody').on('keyup','td.editable', function(e){
                if(e.keyCode == 13){
                    this.innerHTML = this.innerHTML.replace('<br>', '');
                    $(this).attr('contentEditable', false);
                    self.change($(this).parent().find('td').eq(0).text() , $(this).data('key'), $(this).text());
                    return;
                }
            });

            this.$table.on('click', '.deleteRecord', function(){
                var table = self.$table.data("table");
                var id = $(this).parent().find('td').eq(0).text();
                self.dele(table, id);
            });

            $('#add').on('click', function(){
                self.add(self.$table.data("table"));
            });
        }
    }

    table.event();
});